package it.polimi.swKnights.SWIMv2.ejb.abilityManager;

import it.polimi.swKnights.SWIMv2.ejb.authentication.LoginHandlerLocal;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Ability;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.RegisteredUser;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.AlreadyExistingAbilityException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.BadNameAbilityException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class AbilityRequestHandlerRemote
 */
@Stateless
public class AbilityRequestHandler implements AbilityRequestHandlerRemote
{

	@PersistenceContext(unitName = "swimv2-manager")
	private EntityManager managerUC; // manager handling the persistence data
	
	@EJB
	private LoginHandlerLocal loginController;

	@Override
	public void createAbility(String userName, String password, String name, String description)
			throws AlreadyExistingAbilityException, LoginFailException, 
			InvalidLoginPrivilegesException, BadNameAbilityException
	{
		this.loginController.checkLoginDataAndPrivileges(userName, password, RegisteredUser.class);
		this.loginController.checkBanned(userName);
		
		this.checkAbilityGoodName(name);
		
		Ability ability = new Ability(name, description, false, false);
		
		if (this.abilityIsAlreadyPresent(name))
		{
			managerUC.persist(ability);
		}
		else
		{	
			throw new AlreadyExistingAbilityException(" Ability already existentn");
		}
		
		

	}
	
	private void checkAbilityGoodName(String name) throws BadNameAbilityException
	{
		if(name.length() <= 2)
		{
			throw new BadNameAbilityException();
		}
	}

	private boolean abilityIsAlreadyPresent(String name)
	{
		return managerUC.find(Ability.class, name) == null;
	}



}
